package com.ldc.commonres.views

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewStub
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonres.R

class StatusView(context: Context, attributeSet: AttributeSet) :
    FrameLayout(context, attributeSet) {

    private val loadView: View = findViewById(R.id.status_loading)
    private var viewStub: ViewStub? = null
    private var statusView: View? = null
    private var reTryBtn: TextView? = null
    private var textInfo: TextView? = null
    private var ivIcon: ImageView? = null
    private var onRetryClickListener: OnRowListener<Int>? = null


    fun addRetryClickListener(onRetryClickListener: OnRowListener<Int>) {
        this.onRetryClickListener = onRetryClickListener
    }

    fun showContentView() {
        hideStateView()
        hideLoadView()
    }

    fun showLoadView(str: String = "数据加载中，请稍等") {
        loadView.let {
            it.visibility = View.VISIBLE
            textInfo = it.findViewById(R.id.tv_name)
            textInfo?.text = str
        }
        hideStateView()
    }


    fun showEmptyView(str: String = "暂无数据") {
        showStatusView(ViewStateCode.NO_DATA, str)
    }

    fun showErrorView(str: String = "网络异常，请重试") {
        showStatusView(ViewStateCode.ERROR, str)
    }

    private fun initStatusView(): Boolean {
        if (viewStub == null) {
            // viewStub 加载一次，加载完成即不可用
            viewStub = findViewById(R.id.status_change_view)
            statusView = viewStub?.inflate()
            statusView?.let {
                reTryBtn = it.findViewById(R.id.tv_retry)
                textInfo = it.findViewById(R.id.tv_name)
                ivIcon = it.findViewById(R.id.iv_icon)
            }
        }
        return true
    }

    private fun showStatusView(viewStateCode: ViewStateCode, str: String) {
        if (initStatusView()) {
            ivIcon?.setBackgroundResource(if (ViewStateCode.NO_DATA == viewStateCode) R.drawable.res_icon_no_data else R.drawable.res_icon_error)
            reTryBtn?.setOnClickListener { v -> onRetryClickListener?.onRow(v, 0) }
            textInfo?.text = str
            statusView?.visibility = View.VISIBLE
            hideLoadView()
        }
    }

    private fun hideLoadView() {
        loadView.visibility = GONE
    }

    private fun hideStateView() {
        statusView?.let {
            it.visibility = View.GONE
        }
    }
}


enum class ViewStateCode {
    NO_DATA, ERROR
}